<template>
  <div class="login-register-page">
    <div class="container">
      <div class="login-register-card">
        <div class="card-header">
          <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
          <p>{{ isLogin ? '欢迎回来，请登录您的账户' : '欢迎加入我们，请填写注册信息' }}</p>
        </div>

        <div class="form-container">
          <!-- 登录表单 -->
          <el-form
              v-if="isLogin"
              :model="loginForm"
              :rules="loginRules"
              ref="loginFormRef"
              label-width="0"
              @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  size="large"
                  prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  size="large"
                  prefix-icon="Lock"
                  show-password
              />
            </el-form-item>

            <div class="form-options">
              <el-checkbox v-model="rememberMe">记住我</el-checkbox>
              <el-link type="primary" @click="forgotPassword">忘记密码？</el-link>
            </div>

            <el-form-item>
              <el-button
                  type="primary"
                  size="large"
                  class="submit-btn"
                  @click="handleLogin"
                  :loading="loginLoading"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 注册表单 -->
          <el-form
              v-else
              :model="registerForm"
              :rules="registerRules"
              ref="registerFormRef"
              label-width="0"
              @keyup.enter="handleRegister"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="registerForm.username"
                  placeholder="请输入用户名（3-20个字符）"
                  size="large"
                  prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="email">
              <el-input
                  v-model="registerForm.email"
                  placeholder="请输入邮箱地址"
                  size="large"
                  prefix-icon="Message"
                  type="email"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  v-model="registerForm.password"
                  type="password"
                  placeholder="请输入密码（6-20个字符）"
                  size="large"
                  prefix-icon="Lock"
                  show-password
              />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                  v-model="registerForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入密码"
                  size="large"
                  prefix-icon="Lock"
                  show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  size="large"
                  class="submit-btn"
                  @click="handleRegister"
                  :loading="registerLoading"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <p>
              {{ isLogin ? '还没有账户？' : '已有账户？' }}
              <el-link type="primary" @click="toggleForm">
                {{ isLogin ? '立即注册' : '立即登录' }}
              </el-link>
            </p>
          </div>
        </div>
      </div>

      <div class="features-section">
        <div class="feature-item">
          <el-icon class="feature-icon"><Star /></el-icon>
          <h3>精选房源</h3>
          <p>全球优质民宿，为您提供独特住宿体验</p>
        </div>
        <div class="feature-item">
          <el-icon class="feature-icon"><Shield /></el-icon>
          <h3>安全保障</h3>
          <p>严格审核房源，保障您的住宿安全</p>
        </div>
        <div class="feature-item">
          <el-icon class="feature-icon"><Service /></el-icon>
          <h3>贴心服务</h3>
          <p>24小时客服支持，随时为您解决问题</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import request from '../../api/request' // 1. 导入我们封装的 axios 实例

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 表单状态
const isLogin = ref(true)
const loginLoading = ref(false)
const registerLoading = ref(false)
const rememberMe = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度必须在3-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}



// 切换表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
  // 切换时清空表单
  if (loginFormRef.value) loginFormRef.value.resetFields()
  if (registerFormRef.value) registerFormRef.value.resetFields()
}

const handleLogin = async () => {
  const valid = await loginFormRef.value.validate().catch(() => false);
  if (!valid) return;

  loginLoading.value = true;

  try {
    // 直接调用我们封装好的 login Action
    await userStore.loginAction(loginForm);

    ElMessage.success('登录成功！');

    // 跳转到用户之前想去的页面，或者首页
    const redirectPath = router.currentRoute.value.query.redirect || '/';
    router.push(redirectPath);

  } catch (error) {
    console.error('登录流程错误:', error);
    // 错误信息由 axios 拦截器或 store 的 action 统一处理并弹窗
    // ElMessage.error(error.message || '登录失败，请检查用户名和密码');
  } finally {
    loginLoading.value = false;
  }
};

// 类似地，简化 handleRegister
const handleRegister = async () => {
  const valid = await registerFormRef.value.validate().catch(() => false);
  if (!valid) return;

  registerLoading.value = true;

  try {
    await request({
      url: '/api/users/register',
      method: 'post',
      data: {
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password
      }
    });

    ElMessage.success('注册成功！正在为您自动登录...');

    // 注册成功后，自动调用登录逻辑
    await userStore.loginAction({
      username: registerForm.username,
      password: registerForm.password
    });

    router.push('/');

  } catch (error) {
    console.error('注册错误:', error);
  } finally {
    registerLoading.value = false;
  }
};

// 忘记密码
const forgotPassword = () => {
  ElMessageBox.prompt('请输入您的邮箱地址，我们将发送重置密码链接', '忘记密码', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/,
    inputErrorMessage: '请输入正确的邮箱地址'
  }).then(async ({value}) => {
    try {
      // 调用忘记密码API
      await apiRequest('/api/auth/forgot-password', {email: value})
      ElMessage.success(`重置密码链接已发送至 ${value}`)
    } catch (error) {
      ElMessage.error(error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 调试函数 - 查看实际API响应结构
const debugAPIResponse = async () => {
  try {
    const testResponse = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: 'test',
        password: 'test123'
      })
    })
    const result = await testResponse.json()
    console.log('API响应结构:', result)
  } catch (error) {
    console.error('调试请求失败:', error)
  }
}

// 组件挂载时可选调试
// debugAPIResponse()
</script>

<style scoped>
/* 样式保持不变 */
.login-register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 0;
  display: flex;
  align-items: center;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  gap: 40px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.login-register-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 500px;
}

.card-header {
  text-align: center;
  margin-bottom: 30px;
}

.card-header h2 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 10px;
}

.card-header p {
  color: #666;
  font-size: 1rem;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.features-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
  max-width: 500px;
}

.feature-item {
  text-align: center;
  color: white;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.feature-icon {
  font-size: 2.5rem;
  margin-bottom: 15px;
}

.feature-item h3 {
  font-size: 1.3rem;
  margin-bottom: 10px;
}

.feature-item p {
  font-size: 0.95rem;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .login-register-page {
    padding: 20px 0;
  }

  .container {
    flex-direction: column;
  }

  .login-register-card {
    padding: 30px 20px;
  }

  .features-section {
    width: 100%;
  }
}
</style>